package com.nineclock.auth.processor.impl;

import com.nineclock.auth.entity.IntegrationAuthenticationEntity;
import com.nineclock.auth.processor.AuthenticationProcessor;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.system.dto.SysUserDTO;
import com.nineclock.system.feign.SysUserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * 该自定义认证器，主要用于实现  手机号--验证码 的方式认证。
 *  在该认证方式下，前端传递的参数auth_type值为 sms
 */
@Component
public class SmsAuthenticationProcessor implements AuthenticationProcessor {
    @Autowired
    SysUserFeign sysUserFeign;
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;
    @Override
    public SysUserDTO authenticate(IntegrationAuthenticationEntity entity) {
        //取出手机号
        String mobile = entity.getAuthParameter("mobile");
        if (mobile == null){
            throw new NcException(ResponseEnum.MESSAGE_PARAMS_LOST);
        }
        //根据手机号查询
        SysUserDTO sysUserDTO = sysUserFeign.queryUser(mobile).getData();

        if (sysUserDTO != null){
            sysUserDTO.setPassword(bCryptPasswordEncoder.encode("1234"));
        }
        return sysUserDTO;
    }

    @Override
    public boolean support(IntegrationAuthenticationEntity entity) {
        if(entity != null && entity.getAuthType() != null
                && entity.getAuthType().equalsIgnoreCase("sms")){
            return true;
        }
        return false;
    }
}
